<template>
    <div v-if="notFound">
      <div v-show="loadingShow">
        <loading></loading>
      </div>
      <div v-else>
        <div  class="bgf" v-clock>
            
            <router-view></router-view>

            <!--联系人-->
            <confirm-order-custom :custname="initData.userInfo.name" :mobilephone="initData.userInfo.phone"></confirm-order-custom>
            <!-- end 联系人 -->

            <!--服务车辆-->
            <div v-if="carRelation">
                <dl class="normal-bg-t">
                    <dd><span class="label-title">服务车辆：<span class="label-info">{{initData.carModelInfo.carName}}</span></span></dd>
                    <dd v-show="platesShow" style="padding-left:1.8rem;">
                        <span class="gray plates">{{initData.carModelInfo.plates}}</span>
                    </dd>
                    <dd v-else>
                        <span class="seclect-plate-btn" v-link="{path:'/orderservice/ordercarplate',query:{name:carPlate,type:plateType,pathfrom:'cardconfirmorder',skuCodes:this.$route.query.skuCodes}}">{{carPlate}}</span>
                        <input class="plate-text" type="text" v-model="palteText" @input="savePlate('plates', $event)"  placeholder="输入车牌号" maxlength="7" />
                    </dd>
                </dl>
            </div>
            <!--end 服务车辆-->

            <!--服务门店-->
            <confirm-order-store :storeinfo='storeName'></confirm-order-store>
            <!--end 服务门店-->
            
            <!--时间组件-->
            <confirm-order-picktime :choose-time="chooseTime"></confirm-order-picktime>
            <!--end 时间组件-->

            <!--已选服务-->
            <div class="title">
                <div class="left">已选服务</div>
            </div>
            <cardservice></cardservice>
            <!--end 已选服务-->
        </div>



        <!--<div class="pay-confirm" ca="提交订单-确认下单">-->
            
        <!--pay-confirm-->  
        <div class="pay-confirm">
            <input ca="P_卡订单提交$提交订单" type="button" value="确认提交" class="ui-btn" @click="confirm">
        </div>
        <!--end pay-confirm-->
      </div>
    </div>
</template>

<script>
  import cardservice from './card-confirm-order-cardservice';
  import confirmOrderCarplate from '../confirm-order/confirm-order-carplate';
  import confirmOrderCustom from '../confirm-order/confirm-order-custom';
  import confirmOrderStore from '../confirm-order/confirm-order-store';
  import confirmOrderPicktime from '../confirm-order/confirm-order-picktime';
  import common from '../../utils/common';
  
  import Vue from 'vue';
  import {Toast} from 'mint-ui';
  import loading from '../common/loading';

    export default {
        components: {
            cardservice,
            confirmOrderCarplate,
            confirmOrderCustom,
            confirmOrderStore,
            confirmOrderPicktime,
            loading
        },
        
          data() {
            return {
              chooseTime: sessionStorage.getItem("fullday"),// 到店选择时间
              carRelation:true,          
              couponContent: sessionStorage.getItem("chooseCouponContent") ? sessionStorage.getItem("chooseCouponContent") : "未使用", // 券信息
              carPlate: sessionStorage.getItem("choosePlate") ? sessionStorage.getItem("choosePlate") : "沪",// 选择拍照值
              plateType: this.$route.query.type || "c", // 牌照类型c为汉字牌照，l为字母牌照                    
              initData: {
                carModelInfo: {
                  carName: '',
                  plates: ''
                },
                userInfo: {
                  name: '',
                  phone: ''
                }
              },          
              storeName: '',
              storeId: '',
              palteText: '', // 车类型
              loadingShow: true,// Loading 图
              nowTime: '', // 服务器当前时间
              notFound:true,
              platesShow:true,
              loadingShow:true,
              confirmType:true
            }
          },

      route: {
        activate(transition){
          transition.next();
        },
        data: function() {
         
          /*if(sessionStorage.successFalg){
             this.$router.go({name:'mycard'});
             return false;
          }*/
         
          this.carPlate = this.$route.query.name||sessionStorage.getItem("choosePlate") || "沪";
          this.plateType = this.$route.query.type || "c";    
          this.couponContent = sessionStorage.getItem("chooseCouponContent") || "未使用"; // 券信息
          this.couponPrice = sessionStorage.getItem('couponPrice') || 0;
          
              
        }
      },
      ready: function() {
            /*if(sessionStorage.successFalg){
               return false;
            }*/
             console.log("再次");
            common.setTitle('提交订单');  // 设置title
            // 设置值
            var confirmObj = JSON.parse(localStorage.getItem('confirmObj'));
            
            if ( this.isEmptyObj(confirmObj) ) {
                // 显示隐藏模块
//              this.recommendCodeShow = confirmObj.recommendCodeShow, // 推荐码
//              this.carShow = confirmObj.carShow; // 服务车辆模块
//              this.stroeShow = confirmObj.stroeShow; // 服务门店模块
//              this.time = confirmObj.time; // 到店时间模块
                this.orderType = confirmObj.orderType; 
            }
            
            // 设置券码金额
            this.couponPrice = localStorage.getItem('couponPrice');
            
            
            // 处理 Loading图
//                  Vue.http.interceptors.push(function ( request, next ) {
//                      this.loadingShow = true;
//                      next(function ( response ) {
//                          this.loadingShow = false;
//                          return response;
//                      });
//                  });

        
            /**
             * getSelectedElementInfo 
             * 商店 (storeInfo) 和 车辆 (carInfo) 和 购物车 (shoppingCart)
             */
          var _this = this;
          
          this.$http.post(common.isdev()+'/spu/getSelectedElementInfo.htm',{

            targetJumpUrl:window.location.href,
            ssCodes:sessionStorage.getItem("cardServerCodeList")

          }).then(function( d ){
            
              var data = typeof d.data === 'object' ? d.data : JSON.parse(d.data);              
              if (data.result === 1) {                  
                  /**
                   * 订单初始化
                   */
                   //{initType:'06'}
                  _this.$http.post(common.isdev()+'/orderPageInit/init.htm').then(function( d ) {
                    
                   
                    var res = typeof d.data === 'object' ? d.data : JSON.parse(d.data); 

                    if ( res.result === 1 ) {
                        
                    // 获取服务器当前时间
                    this.nowTime=res.obj.currentTime;
                    this.$broadcast('sendTime', [this.nowTime,""]);
                    this.loadingShow = false;
                      _this.initData.carModelInfo = data.obj.carInfo || '';
                      _this.initData.userInfo = res.obj.userInfo || '';
                      _this.storeName = res.obj.storeInfo.storeName || '';
                      
                      if(!_this.initData.carModelInfo.plates){
                        _this.platesShow = false;
                      }

                      //判断用户信息如果为null
                      if(_this.initData.userInfo.name == null || _this.initData.userInfo.name == 'null'){

                        if(sessionStorage.username){
                          _this.initData.userInfo.name = sessionStorage.username;
                        }else{
                          sessionStorage.username = '';
                          _this.initData.userInfo.name = '';
                        }
                        
                      }
                      //向缓存中添加用户名
                      sessionStorage.setItem("username",_this.initData.userInfo.name);
                      
                      var payOnline = [], payOnStore = [], prmName = [], totalPrice = 0, payTotalPrice=0, scode = [];
                      var obj = res.obj;
                      

                    } else if ( res.result === 0 ) {
                        /******** 修改404页面 ********/
                        this.notFound = false;
                        common.goNotFound();
                        /******** 修改404页面 ********/
                        //Toast(res.message);
                    }
                                
                    // 判断是否登陆
                    if ( res.result === -99 ) {
                      common.goLogin();
                    }
                    
                  }, function( err ) {
                    Toast(err);
                  });
                
              } else if ( res.result === 0 ) {
                  /******** 修改404页面 ********/
                  this.notFound = false;
                  common.goNotFound();
                  /******** 修改404页面 ********/
              }
    
          }, function( err ) {
            Toast(err);
          });
          common.ANA_Analytics();
      },
      
      methods: {    
          
          // 提交
          confirm: function() {
            var _this = this;
             // 修改日期
            var curTime = '';
            //防止重复提交
            if(_this.confirmType){
              _this.confirmType = false;
            }else{
              Toast("请不要重复提交");
              return false;
            }
            //设定网络超时恢复
            setTimeout(function(){
              _this.confirmType = true;
            },20000);
           
            if ( sessionStorage.getItem("fullday") && sessionStorage.getItem("fullday") !== 'undefined' && sessionStorage.getItem("fullday") !== 'null' ) {
                curTime = sessionStorage.getItem("fullday");
            } else {
                curTime = this.timestamp(Date.parse(new Date()));
            }
            var _reservationDateStr = curTime.replace(/[\u4e00-\u9fa5]/g, '/');
            if ( _reservationDateStr.substring(_reservationDateStr.length - 1) === '/' ) {
                _reservationDateStr = _reservationDateStr.substring(0, _reservationDateStr.length-1);
            }
            

            // 车牌
            var plates = '';

            // 验证是否填写正确车辆
            if ( _this.initData.carModelInfo.plates ) {
                plates = _this.initData.carModelInfo.plates;
            } else if( _this.palteText ) {
                plates = _this.carPlate + _this.palteText;  

                var isPlate = /^[A-Z]{1}[A-Z_0-9]{5,6}$/; // 车牌正则验证

                if(!isPlate.test(_this.palteText)) {
                    Toast("车牌格式错误！");
                    return false;
                }
            } else {
                Toast('请填写车牌');
                return false;
            } 
           
            
            // 修改联系人
            var contactName = '';
            var isName = /^[A-Za-z\u4e00-\u9fa5]+$/; //只能输入中英文
            if ( sessionStorage.getItem('username') ) {

              if(!isName.test(sessionStorage.getItem('username'))){
                  Toast('仅限输入中英文');
                  return false;
              }else{
                contactName = sessionStorage.getItem('username');
              }

            } else {
                Toast('请填写联系人');
                return false;
            }
            


            // 所选择的卡服务
            var cardSelectServer = [];
            var selectServer = JSON.parse(sessionStorage.cacheSeverLocalStorage);
            delete selectServer.serverLength;
            for(var item in selectServer) {
                cardSelectServer.push({
                    quality: '1',
                    skuCode: selectServer[item].skuCode,
                    sCode:selectServer[item].serviceNo
                });
            }
            // 提交订单数据组合
            var fedOrderVOString = JSON.stringify({

              packageCard: localStorage.thisCardNo,

              cardTemplateNo:sessionStorage.cardTemplateNo,//卡模板ID
              // 结算订单商品VO 数量+skuCode
              settle: cardSelectServer, 

              // 订单类型   [01,线上售卡][02,普通服务][03,轮胎服务][04,洗车服务][05,套餐卡服务][06,套餐卡用卡]</p>
              orderCommitType: '06',  

              // 车信息
              // carModelInVo: {carId:'001',plates:'苏HDN218',carName:'朗逸',assetId:'1'},
              carModelInVo: { plates: plates },

              // 联系人
              contactName: contactName,
              
              // 到店日期        
              reservationDateStr: _reservationDateStr,

              // 上午 下午          
              remark: sessionStorage.getItem("remark"),  

              // 券码                 
              //coupon: { couponCode: _couponCode },

              // 门店信息  
              storeInfo: _this.initData.storeInfo
              
              // 推荐码
//            recommendCode: recommendCode 
            }); 


            
            /**
             * 提交订单
             */
            this.$http.post(common.isdev()+'/orderFollow/orderHandle.htm',{
              fedOrderVO: fedOrderVOString
            }).then(function ( d ) {
              
              var res = typeof d.data === 'object' ? d.data : JSON.parse(d.data);
              

              if ( res.success ) {
                                // 判断是否跳转支付页面
                if ( res.statusCode == '000009' ) {
                    sessionStorage.successLink = '';
                    sessionStorage.successLink = '/order/detail_preorder_'+res.orderHeadCode+'.htm';
                    sessionStorage.successFalg = true;
                    this.confirmType = true;//防止重复提交
                    this.$router.go({name:'success'});
                } else {
                    this.confirmType = true;
                    window.location.href = res.payURL;
                }
                
              } else {

                var cardServerData = JSON.parse(localStorage.thisCardServer).cardItemVo;
                if(res.skuCode || res.skuCode != null){
                  
                  for(var i = 0; i < cardServerData.length; i++){

                    if(cardServerData[i].skuCode == res.skuCode){
  
                      if(res.errorCode == '0004'){
                        Toast('所选门店不支持「'+cardServerData[i].serviceName+'」服务，请重新选择');
                        this.confirmType = true;//防止重复提交
                        return false;
                      }else{
      
                        Toast('所选服务「'+cardServerData[i].serviceName+'」暂不可用');
                        this.confirmType = true;//防止重复提交
                        return false;
                      }
                    }

                  }
                }else{

                  console.log((res.messages[0]));
                  Toast(common.queryCodeMessage(res));
                  this.confirmType = true;//防止重复提交
                }
                
              }
              
            }, function( err ) {
              console.log(JSON.stringify(err) + '--订单提交出错');
              this.confirmType = true;//防止重复提交
            });
            
          },
          
          /**
           * 处理车牌第二次返回无显示
           */
          savePlate: function (plates, event) {
            
            var val = this.palteText ? this.palteText : '';
            val = this.converToUpperCase(val) || '';

            var isPlate = /^[A-Z]{1}[A-Z_0-9]{5,6}$/;

            
            // 大于6位截取
            if ( val.length > 7 ) {
              val = val.substr(0, 7);
            }
            // 去除中文,特殊字符,并且转换大写
            val = this.trim(this.removeCn(val));
      
            // 验证车牌
            if ( val.length >= 6 ) {
              if ( !isPlate.test(val) ) {
                Toast('车牌格式错误');
            }
            }
            this.palteText = val;
            localStorage.setItem(plates, val);

          },
          /**
           *  去除前后空格
           * @param {String} str
           * @reutrn {String} 
           */
          trim: function ( str ) {
                if ( str ) {
                return str.replace(/(^\s*)|(\s*$)/g, "");
                }
                return '';
          },
          /**
           * 转换大写
           * @param {String} str 转换的字符串
           * @return {Mixin} Boolean String  
           */
          converToUpperCase: function ( str ) {
            if ( str ) {
              if ( !str && str == 'undefined' && str == 'null' ) {
                return false;
              }
              
              var first = str.toUpperCase();
              
              return first;
            }
          },
          /**
           * 去除字符串中的中文
           * @param {String} str 需要的字符串
           * @return {String} 去除中文和特殊字符串
           */
          removeCn: function( str ) {
            var rep = /[\u4E00-\u9FA5]|[!+|@+|#+|$+|%+|^+|&+|*+|(+|)+|,+|.+|>+|<+|/+|?+|~+|`+|,+|.+|<+|>+|/+|?+]/g;
            return str && str.replace(rep, '').toUpperCase();
          },
          /**
           * 处理 年月日 时间
           * @param {Object} time 事件戳
           * @return {String} 年月日时间
           * @example 2016/11/6  
           */
          timestamp: function( time ) {
            
              var date = new Date(time);
              var Y = date.getFullYear() + '/';
              var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';
              var D = date.getDate() + ' ';
              
              return Y + M + D;
              
          },
                    
            /**
             * 判断是否为空的对象
             * @param {Object} obj
             * @return {Boolean} 
             */
            isEmptyObj: function ( obj ) {
                var num = 0;
                for ( var i in obj ) {
                    num++;
                }
                return num > 0 ? true : false;
            },

      },
          events: {
            'chooseTime-dispatch'() {
          this.chooseTime = sessionStorage.getItem("fullday");
            }
          }
    }

</script>


<style lang="scss" scoped>

    @import '../../assets/css/_functions.scss';
    @import '../../assets/css/_variables.scss';
    .normal-bg-t {
        padding-left: 0 !important; 
    }
    .bgf {
        background-color: #fff;
        .recommend-code {
            width: 100%;
            height: rem(48);
            line-height: rem(48);
            padding-left: rem(14);
            color: $_333;
            font-size: rem(14);
            input {
                border: none;
                background: $_fff;
                padding-left: rem(5);
            }
        }
    }
    .normal-bg-t {
        background-color: $_fff;
        font-size: rem(14);
    }
    .normal-bg {
        background-color: $_fff;
        padding: rem(12) rem(15);
        font-size: rem(14);
        i {
            margin-right: rem(5);
        }
    }
    
    .normal-bg-t {
        clear: both;
        overflow: hidden;
        height: rem(44);
        line-height: rem(44);
        margin:0 rem(20);
        border-bottom: 1px solid #dedede;
        dd {
            float: left;
        }
        dd:first-child {
            display: inline-block;
            width: rem(200);
            height: rem(44);
            .label-title{
            	display: block;
    			    width: 100%;
    			    white-space: nowrap;
    			    text-overflow: ellipsis;
    			    overflow: hidden;
            }
            .label-info{
              font-size:1.32rem;
              color:#999;
            }
        }
        .plates{
          font-size:1.32rem;
        }
        .picktime {
            width: rem(105);
        }
        dd:last-child {
            float: right;
            padding-right: rem(15);
        }
    }
    
    ul {
        li {
            border-bottom: 1px solid #c8c7cc;
            p {
                color: $_666;
                line-height: rem(30);
                font-size: rem(13);
            }
            h3 {
                line-height: rem(27);
            }
            h4 span:last-child {
                font-size: rem(13);
            }
        }
        li:last-child {
            border-bottom: 0;
        }
    }
    .couponPrice {
        color: $_666;
    }
    ul li p span:last-child,
    ul li h3 span:last-child,
    ul li h4 span:last-child {
        float: right;
    }
    
    .seclect-plate-btn {
        background: #0299f6 url(../../assets/images/arrow-b.png) no-repeat rem(20) center;
        background-size: rem(9) rem(6);
        display: inline-block;
        width: rem(30);
        height: rem(24);
        border-radius: rem(4);
        line-height: rem(24);
        color: #fff;
        padding-left: rem(4);
    }
    
    .plate-text {
        background: none;
        border: none;
        width: rem(70);
        margin-top: rem(-4);
        margin-left: rem(7);
        color: #243742;
    }
    
    i {
        color: $_999;
    }
    
    .username-text {
        background: none;
        border: none;
        width: rem(96);
        margin-top: rem(-4);
        color: #243742;
    }
    
    .amount {
        height: rem(30);
        line-height: rem(30);
        text-align: right;
        padding-top: rem(5);
        padding-right: rem(15);
    }
    
    .num {
        color: #f00;
        font-size: rem(16);
    }
    
    .num small:first-child {
        margin: 0 rem(5);
    }
    
    .mb40 {
        margin-bottom: rem(80);
    }
    
    .no-pd-r {
        padding-right: 0;
    }
    
    .no-pd-r p, .no-pd-r h3 {
        padding-right: rem(15);
    }
    
    .ticket {
        background: transparent url(../../assets/images/arrow.png) no-repeat right 0.3rem;
        padding-right: rem(12);
    }
    .phone-num {
        background: transparent url(../../assets/images/phone.png) no-repeat left center;
        padding-left: rem(15);
    }
    .pd-b8 {
        padding-bottom: rem(8);
    }
    .pay-confirm {
        width: 100%;
        background: #fafbfc;
        position: fixed;
        bottom: 0;
        z-index: 10;
        border-top: 1px solid #e7e7e7;
        dl {
            dt {
                float: left;
                font-size: rem(14);
                padding-left: 1.5rem;
                p {
                    display: table-cell;
                    height: rem(48);
                    vertical-align: middle;
                }
                small:first-child {
                    margin: 0 rem(5)
                }
                .s {
                    font-size: rem(12);
                }
            }
            dd {
                float: right;
            }
        }
        .ui-btn {
            width: 100%;
            height: rem(48);
            line-height: rem(48);
            background-color: #ff6600;
            font-size: rem(18);
            color: #fff;
            border: none;
        }
    }
    .title{
        display: flex;
        align-items: center;
        width: rem(375);
        height: rem(55);
        background: #fff;
        font-size: rem(14);
        color: #333;
        padding-left: rem(20);
        padding-right: rem(14);
}
</style>